/* 
 * @name customers.js
 * @author : Amissah Gideon<kuulmek@yahoo.com>
 */
var Customer = {
    /* Server script url   */
    ssUrl:'Customers/add',
    selected_row_id:null,

    /* dataTable Object */
    objGrid:null,

    /* Function init
     * @param void
     * @return void
     * @access public
     * */
    init:function () {
        var self = this;

        Calendar.setup({
            inputField:"date_of_commence",
            trigger:"date_of_commence_btn",
            onSelect:function () {
                this.hide()
            },
            dateFormat:"%B %d, %Y",
            showTime:false,
            animation:true
        });

        /*Sortable Table */
        var oTable = null;
        var dataUrl = $('#table-url').val();

        self.objGrid = $('#flex').flexigrid({
            url:dataUrl,
            dataType:'json',
            colModel:[
                {display:'ID', name:'id', width:20, sortable:false, align:'left', hide:true},
                {display:'Name', name:'name', width:140, sortable:true, align:'center', hide:false},
                {display:'Contact Person', name:'contact_person', width:140, sortable:true, align:'center', hide:false},
                {display:'Telephone', name:'phone_number', width:140, sortable:true, align:'center', hide:false},
                {display:'Email', name:'email', width:140, sortable:true, align:'center', hide:false},
                {display:'Address', name:'address', width:140, sortable:true, align:'center', hide:false},
                {display:'City', name:'city', width:140, sortable:true, align:'center', hide:false},
                {display:'Region', name:'region_id', width:140, sortable:true, align:'center', hide:false}
            ],
            formFields:[
                {type:'buttom', name:'Add', bclass:'add', onpress:self.handleGridEvent},
                {separator:true},
                {type:'buttom', name:'Edit / View', bclass:'edit', onpress:self.handleGridEvent},
                {separator:true},
                {type:'buttom', name:'Delete', bclass:'delete', onpress:self.handleGridEvent},
                {separator:true},
                {type:'buttom', name:'Upload Customer Picture', bclass:'upload', onpress:Customer.handleGridEvent}
            ],
            searchitems:[
                {display:'Name', name:'name', isdefault:true},
                {display:'Telephone', name:'phone_number'},
                {display:'Email', name:'email'},
                {display:'Address', name:'address'},
                {display:'City', name:'city'},
                {display:'Region', name:'region_name'}
            ],
            checkboxSelection:true,
            columnControl:true,
            sortname:"id",
            sortorder:"desc",
            usepager:true,
            useRp:true,
            rp:15,
            showTableToggleBtn:false,
            height:300
        });

        $('#save-btn').click(function () {
            self.save();
        });

        $('#cancel-btn').click(function () {
            document.getElementById('form').reset();
            $.validationEngine.closePrompt('.formError', true);
            $.colorbox.close();
            self.selected_row_id = null;
        });

        jLib.afterClosePopUpForm('form', function () {
            self.selected_row_id = null;
            document.getElementById('form').reset();
        });

        $("#form").validationEngine();

    },

    handleGridEvent:function (com, grid) {
        if (com == 'Add') {
            $('#form-window #form #pic_placeholder').hide();
            $.colorbox({
                inline:true,
                scrolling:false,
                overlayClose:false,
                escKey:false,
                title:'Customer Information',
                href:"#form-window"
            });
            $('#form-window #form #country_id').val('82');
            $('#form-window #form #country_id').change();
        }
        else if (com == 'Edit / View') {
            if (jLib.rowSelectedCheck(grid, 1)) {
                Customer.edit(jLib.getSelectedRowIds(grid));
            }
        }
        else if (com == 'Delete') {
            if (jLib.rowSelectedCheck(grid)) {
                Customer.delete_(grid);
            }
        }
        else if (com == 'Upload Customer Picture') {
            if (jLib.rowSelectedCheck(grid, 1)) {
                Customer.uploadPic(jLib.getSelectedRowIds(grid));
            }
        }
    },

    uploadPic:function (customer_id) {
        var url = $("#upload-url").val()+'/'+customer_id;
        window.open(url, "ImportWindow", "menubar=yes, width=350, height=250,location=no,status=no,scrollbars=yes,resizable=yes");
    },

    edit:function (row_ids) {
        var self = this;

        var dataID = row_ids[0];
        var url = $('#load-user-url').val();
        var query = 'type=load&data-id=' + dataID;

        $('#form-window #form #pic_placeholder').hide();

        $.ajax({
            url:url,
            data:query,
            dataType:'json',
            type:'POST',
            success:function (response) {
                var txt = '';
                if (typeof response.mesg == 'object') {
                    for (megTxt in response.mesg) {
                        txt += response.mesg[megTxt] + '<br />';
                    }
                }
                else {
                    txt = response.mesg
                }
                //* When everything went on smoothly on the server redirect the user to the appropriate page.*//*
                if (response.code === 0) {
                    var data = response.data.Customer;

                    $('#form-window #form #name').val(data.name);
					$('#form-window #form #customer_type').val(data.customer_type);
                    $('#form-window #form #customer_type').change();
                    $('#form-window #form #phone_number').val(data.phone_number);
                    $('#form-window #form #email').val(data.email);
                    $('#form-window #form #certificate_no').val(data.certificate_no);
                    $('#form-window #form #date_of_commence').val(jLib.convertDate(data.date_of_commence, 'ui'));
                    $('#form-window #form #contact_person').val(data.contact_person);
                    $('#form-window #form #address').val(data.address);
                    $('#form-window #form #region_id').val(data.region_id);
                    $('#form-window #form #region_id').change();
                    $('#form-window #form #city').val(data.city);
                    $('#form-window #form #physical_location').val(data.physical_location);
                    $('#form-window #form #country_id').val(data.country_id);
                    $('#form-window #form #country_id').change();
                    $('#form-window #form #comments').val(data.comments);

                    var path = $('#form-window #form #pic_placeholder').attr('path');
                    var file_name = data.pic_filename;
                    console.log(typeof file_name)
                    if(typeof file_name != 'string'){
                        file_name = 'temp.png';
                    }
                    path += file_name;
                    $('#form-window #form #pic_placeholder').attr('src',path);
                    $('#form-window #form #pic_placeholder').show();

                    self.selected_row_id = dataID;

                    $.colorbox({
                        inline:true,
                        scrolling:false,
                        overlayClose:false,
                        escKey:false,
                        title:'Customer Information',
                        href:"#form-window"
                    });
                }
                //* When there are Errors *//*
                else if (response.code === 1) {
                    jLib.serverError(txt);
                }
            },
            error:function (xhr) {
                console.log(xhr.responseText);
                jLib.serverError();
            }
        });

    },

    save:function () {
        var self = this;
        /* Validate the form*/
        var validationStatus = $('#form').validationEngine({returnIsValid:true});
        /* When the Validation Status is true meaning that the data input are correct then the data can be processed. */
        if (validationStatus) {

            jLib.showFormLoading();

            var query = 'model=Customer&row_id=' + self.selected_row_id + '&' + $('#form').serialize();
            /* Send the data to the server and handle the server response */
            var url = $("#add-edit-url").val();


            $.ajax({
                url:url,
                data:query,
                dataType:'json',
                type:'POST',
                success:function (response) {
                    var txt = '';
                    if (typeof response.mesg == 'object') {
                        for (megTxt in response.mesg) {
                            txt += response.mesg[megTxt] + '<br />';
                        }
                    }
                    else {
                        txt = response.mesg
                    }
                    //* When everything went on smoothly on the server redirect the user to the appropriate page.*//*
                    if (response.code === 0) {

                        jLib.message(txt, 'success');

                        if (self.selected_row_id) {

                            var cedi_amount = 0.00;
                            if ($('#form-window #form #currency').val() == '$') {
                                cedi_amount = parseFloat($('#form-window #form #amount').val()) * parseFloat($('#form-window #form #usd_rate').val());
                            }
                            else {
                                cedi_amount = $('#form-window #form #amount').val();
                            }
                            // Chnge the cell data
                            update_data = {
                                'name':$('#form-window #form #name').val(),
                                'contact_person':$('#form-window #form #contact_person').val(),
                                'phone_number':$('#form-window #form #phone_number').val(),
                                'email':$('#form-window #form #email').val(),
                                'address':$('#form-window #form #address').val(),
                                'city':$('#form-window #form #city').val(),
                                'region_id':$('#form-window #form #region_id option:selected').text()
                            };

                            jLib.updateGridData(self.objGrid, update_data);
                            //
                            jLib.highlightRow(self.objGrid);
                        }
                        else {
                            $(self.objGrid).flexReload();
                            var content = "<p class='message icon-speech orange-gradient small-margin-bottom'></span>Would you like upload customer's picture ?</span></p>"
                            $.modal({
                                contentBg:false,
                                contentAlign:'center',
                                content:content,
                                resizable:false,
                                actions:{},
                                buttons:{
                                    'Yes':{
                                        classes:'gray-gradient',
                                        click:function (modal) {
                                            Customer.uploadPic(response.data.id);
                                            modal.closeModal();
                                        }
                                    },
                                    'No':{
                                        classes:'gray-gradient',
                                        click:function (modal) {
                                            modal.closeModal();
                                        }
                                    }
                                },
                                buttonsAlign:'center'
                            });

                        }
                        document.getElementById('form').reset();
                        $.validationEngine.closePrompt('.formError', true);
                        $.colorbox.close();
                        self.selected_row_id = null;
                    }
                    //* When there are Errors *//*
                    else if (response.code === 1) {
                        jLib.serverError(txt);
                    }

                    jLib.hideFormLoading();
                },
                error:function (xhr) {
                    console.log(xhr.responseText);
                    jLib.serverError();
                }
            });
        }
    },


    delete_:function (grid) {
        var self = this;
        var url = $('#delete-url').val();
        jLib.do_delete(url, grid);
    }

};


/* when the page is loaded */
$(document).ready(function () {
    Customer.init();
});